//
//  FlashSaleViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/25.
//

import UIKit

class FlashSaleViewController: BaseViewController {
    var itemMenuView = MLMSegmentHead()
    var scrollView: MLMSegmentScroll!
    var bgImageView: UIImageView!
    var saleModel: PromotionCotentModel!
    var categoryArray: [CategoryListModel] = []
    var timeView: UIView!
    var timer: Timer!
    var timeCount: NSInteger = 0
    var viewArray: [StoreListTableView] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.initNav()
        self.initTopBgImageView()
        self.requestCategoryList()
        
    }
    
    func initNav(){
        let shareBtn = UIButton(frame: CGRect(x: kScreenWidth - 44, y: NavBarHight - 35, width: 30, height: 30))
        shareBtn.setImage(UIImage(named: "icon_normal_share"), for: .normal)
        shareBtn.addTarget(self, action: #selector(shareBtnAntion), for: .touchUpInside)
        shareBtn.isHidden = false
        self.navBar.addSubview(shareBtn)
    }

    func initTopBgImageView(){
        self.bgImageView = UIImageView(frame: CGRect(x: 14, y: NavBarHight, width: kScreenWidth - 28, height: 210))
//        self.bgImageView.contentMode = .scaleAspectFit
        self.view.addSubview(self.bgImageView)
        
       let language = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.kAppLanguage)
        if language.contains("hk"){
            self.bgImageView.image = UIImage(named: "icon_flash_hk")
        }else if language.contains("en"){
            self.bgImageView.image = UIImage(named: "icon_flash_en")
        }else{
            self.bgImageView.image = UIImage(named: "icon_flash_ch")
        }
        
        self.requestFlashCaleData()
        
    }
    
    
    //限时抢购
    func requestFlashCaleData(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.flashCale, objectType: FlashCaleModel.self) { data in
            let resultObj = data as! FlashCaleModel
            if resultObj.code == "1" {
                let promotionModel = resultObj.data?.promotion
                self.timeCount = (promotionModel?.activityTime ?? 0)/1000
                self.timeSende()
            }
        } error: { err in
            
        }
    }
    
    
    func timeSende(){
        
        self.timeView = UIView(frame: CGRect(x: (self.bgImageView.frame.size.width - 170)/2, y: 130, width: 170, height: 26))
        self.timeView.backgroundColor = UIColor(hex: 0xFFBBA6)
        self.timeView.layer.cornerRadius = 13
        self.timeView.layer.masksToBounds = true
        self.bgImageView.addSubview(self.timeView)
        
        let timeStr = XTManageCenter.calculateDateTimeFromNowBySecond(ms: self.timeCount)
        let tempArray = timeStr.components(separatedBy: ":")//
        let width: CGFloat = (self.timeView.frame.size.width - CGFloat((tempArray.count * 40)))/2
        for index in 0 ..< tempArray.count {
            let timeBtn = UIButton(frame: CGRect(x: Int(width) + (index * 40), y: 0, width: 40, height: 26))
            timeBtn.setTitleColor(Theme.redColor, for: .normal)
            timeBtn.setTitle(tempArray[index], for: .normal)
            timeBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 12)
            timeBtn.isUserInteractionEnabled = false
            self.timeView.addSubview(timeBtn)
            timeBtn.tag = 60000 + index
            
            let dinLab = UILabel(frame: CGRect(x: timeBtn.right, y: 0, width: 3, height: 26))
            dinLab.text = ":"
            dinLab.font = UIFont(name:Theme.PingFangSCMedium, size: 12)
            dinLab.textColor = Theme.redColor
            self.timeView.addSubview(dinLab)
            
            if index == 0  {
                dinLab.isHidden = true
            }
            if (tempArray.count - 1) == index{
                dinLab.isHidden = true
            }
        }
        
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self , selector: #selector(timeAction), userInfo: nil, repeats: true)
        RunLoop.current.add(self.timer, forMode: RunLoopMode.commonModes)
        
    }
    
    
    @objc func timeAction(){
        if self.timeCount > 0 {
            self.timeCount = self.timeCount - 1
            let tempStr = XTManageCenter.calculateDateTimeFromNowBySecond(ms: self.timeCount)
            let tempArray = tempStr.components(separatedBy: ":")
            
            let dayBtn = self.timeView.viewWithTag(60000) as? UIButton
            dayBtn?.setTitle(String(format: "%@", tempArray[0]), for: .normal)
            
            let hourBtn = self.timeView.viewWithTag(60001) as? UIButton
            hourBtn?.setTitle(String(format: "%@", tempArray[1]), for: .normal)
            
            let minuteBtn = self.timeView.viewWithTag(60002) as? UIButton
            minuteBtn?.setTitle(String(format: "%@", tempArray[2]), for: .normal)
            
            let secondBtn = self.timeView.viewWithTag(60003) as? UIButton
            secondBtn?.setTitle(String(format: "%@", tempArray[3]), for: .normal)
            
        }else{
            //说明今天的秒杀已过
            self.timeCount = 0
            if self.timer != nil {
                self.timer.invalidate()
                self.timer = nil
            }
            
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "mainRefreash"), object: nil)
           //刷新
        }
    }
    
    // MARK: - Privately
    func initTopMenu(titleArra: [String]) {
     
        self.itemMenuView = MLMSegmentHead.init(frame: CGRect.init(x: 0, y: self.bgImageView.frame.maxY + 10 , width: kScreenWidth, height: 34), titles: titleArra, headStyle: MLMSegmentHeadStyle.init(1), layoutStyle: MLMSegmentLayoutLeft)
        self.itemMenuView.backgroundColor = .white
        self.itemMenuView.fontScale = 1
        self.itemMenuView.slideHeight = 1
        self.itemMenuView.lineHeight = 3
        self.itemMenuView.linePaddingBottom = 6
        self.itemMenuView.lineWidth = 24
        self.itemMenuView.fontSize = 14
        self.itemMenuView.unSelectFont = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        self.itemMenuView.selectedFont = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.itemMenuView.deSelectColor = Theme.titleLabColor
        self.itemMenuView.headColor = .clear
        self.itemMenuView.lineColor = Theme.mainColor
        self.itemMenuView.selectColor = Theme.mainColor
        self.itemMenuView.bottomLineHeight = 0

 
        
       let hh = kScreenHeight - NavBarHight - self.bgImageView.frame.size.height - 38
        //装所有的tableView
        var tempViewArr: [StoreListTableView] = []
        for index in 0 ..< titleArra.count{
            let model = self.categoryArray[index]
            let ww: CGFloat =  CGFloat(index) * kScreenWidth
            let tableView = StoreListTableView(frame: CGRect(x: 0, y: self.bgImageView.frame.maxY + 38, width: ww, height: hh))
            tableView.backgroundColor = .white
            tableView.categoryId = model.id ?? 0
            tableView.isFlashMore = true
            tableView.promotionId = self.saleModel.promotionId ?? 0
            if index == 0 {
                tableView.roadRefreash()
            }
            tempViewArr.append(tableView)
        }
        self.viewArray = tempViewArr

        self.scrollView = MLMSegmentScroll(frame: CGRect(x: 0, y: self.bgImageView.frame.maxY + 38, width: kScreenWidth, height: hh), vcOrViews: viewArray)
        self.scrollView.addScale = 0.1
        self.scrollView.loadAll = false
        self.scrollView.backgroundColor = .clear
        self.scrollView.showIndex = 0//展示那个
        
        //绑定
        MLMSegmentManager.associateHead(self.itemMenuView, with: self.scrollView, contentChangeAni: true) {
            self.view.addSubview(self.itemMenuView)
            self.view.addSubview(self.scrollView)
        } selectEnd: { index in
            guard self.viewArray.count > index else {
                return
            }
            self.viewArray[index].roadRefreash()
        }

    }
    
    
    //MARK: - Requset
    //商品类型查询接口
    func requestCategoryList(){
        
//        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getCategoryList(param: ["level": "1"]), objectType: CategoryModel.self) { data in
//            let resultObj = data as! CategoryModel
//            if resultObj.code == "1" {
//                self.categoryArray.addObjects(from: resultObj.data ?? [])
//                let allModel = CategoryListModel.init()
//                allModel.id = -1
//                allModel.name = MMLocalizedString("total", comment: "全部")
//                self.categoryArray.insert(allModel, at: 0)
//            }
//            let titleArray = self.categoryArray.compactMap{$0 as? CategoryListModel}.map{$0?.name ?? ""}
//            self.initTopMenu(titleArra: titleArray)
//
//        } error: { err in
//            self.view.makeToastBottom(message: err?.domain ?? "")
//        }
        
        let param: [String: String] = ["promotionId": "\(self.saleModel.promotionId ?? 0)"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.moreFlashSaleList(param: param), objectType: MoreFlashSaleModel.self) { data in
            let resultObj = data as! MoreFlashSaleModel
            if resultObj.code == "1" {
                let tempList = resultObj.extData?.categoryList ?? []
                self.categoryArray = tempList
                
                //插入全部
                let allModel = CategoryListModel.init()
                allModel.id = -1
                allModel.name = MMLocalizedString("total", comment: "全部")
                self.categoryArray.insert(allModel, at: 0)
            }
            
            let titleArray = self.categoryArray.map{$0.name ?? ""}
            self.initTopMenu(titleArra: titleArray)
        } error: { err in
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    //MARK: - Antion
    //分享
    @objc func shareBtnAntion() {
        if  self.saleModel == nil{
            return
        }
        let VC = ShareViewController()
        VC.titleStr = MMLocalizedString("share", comment: "分享")
        VC.isfaceBook = true
        let shareText = XTManageCenter.getLocalStringDataValue(aKey: "shareText")
        VC.shareContent = shareText
        VC.shareUrl = shareText 
        VC.modalPresentationStyle = .overFullScreen
        self.present(VC, animated: false, completion: nil)
    }
}
